package com.td.evo.log.cross;

import com.krakers.evo.log.EvolutionLogic;
import com.krakers.evo.log.cross.AbstractSimpleCrosser;
import com.krakers.evo.obj.DNA;
import com.td.core.obj.TDMap;
import com.td.evo.log.TDPathEvolutionLogic;

public class TDSimplePathCrosser extends AbstractSimpleCrosser implements TDMap {

	private static final int X = BLD_X/2;
	private static final int Y = BLD_Y/2;
	
	public TDSimplePathCrosser(int elite) {
		super(elite);
	}
	
	@Override
	protected void crossInternal(DNA p1, DNA p2) {
		int g = EvolutionLogic.r.nextInt(p1.getSize());
		DNA c1 = new DNA(p1.getSize());
		DNA c2 = new DNA(p2.getSize());
		
		p1.copyChain(c1, 0, g);
		p2.copyChain(c2, 0, g);
		p1.copyChain(c2, g, p1.getSize());
		p2.copyChain(c1, g, p2.getSize());
		
		correctDNA(c1, g);
		correctDNA(c2, g);
		
		c1.copyChain(p1);
		c2.copyChain(p2);
	}
	
	private void correctDNA(DNA dna, int g) {
		if((g/X)%2 != 0) {
			TDPathEvolutionLogic.fillOnes(dna, g/X);
			
			int z1 = g%X;
			if(g/X-1 > -1)
				z1 = TDPathEvolutionLogic.getZeroIndx(dna, g/X-1);
			int z2 = g%X;
			if(g/X+1 < Y)
				z2 = TDPathEvolutionLogic.getZeroIndx(dna, g/X+1);
			
			TDPathEvolutionLogic.fillZeros(dna, g/X, z1, z2);
		} else {
			//popraw srodek
			TDPathEvolutionLogic.fillOnes(dna, g/X);
			dna.setGene(g, 0);
			
			//popraw gore
			if(g/X > 1) {
				int z = TDPathEvolutionLogic.getZeroIndx(dna, g/X - 2);
				TDPathEvolutionLogic.fillOnes(dna, g/X - 1);
				TDPathEvolutionLogic.fillZeros(dna, g/X - 1, z, g%X);
			}
			
			//popraw dol
			if(g/X < Y-2) {
				int z = TDPathEvolutionLogic.getZeroIndx(dna, g/X + 2);
				TDPathEvolutionLogic.fillOnes(dna, g/X + 1);
				TDPathEvolutionLogic.fillZeros(dna, g/X + 1, z, g%X);
			}
		}
	}
}
